import getpass
import time

import pytest
from playwright.sync_api import sync_playwright, Playwright
from conf import TEST_URL
from page.home.home_page import  LoginPage

from utils.log import LoggerUtils
from utils.send_email import send_email
from utils.send_feishu import inform


# __USER_DATE_DIR_PATH__ = f"C:\\Users\\{getpass.getuser()}\\AppData\Local\Google\Chrome\\User Data"
# __EXECUTABLE_PATH__ = f"C:\Program Files\Google\Chrome\Application\chrome.exe"
#
#
# @pytest.fixture(scope="function", autouse=True)
# def page(playwright: Playwright):
#     browser = playwright.chromium.launch_persistent_context(
#         user_data_dir=__USER_DATE_DIR_PATH__,
#         executable_path=__EXECUTABLE_PATH__,
#         headless=False,
#         # bypass_csp=True,
#         # slow_mo=10,
#         args=["--disable-blink-features=AutomationControlled"]
#     )
#     page = browser.new_page()
#
#     page.wait_for_load_state("networkidle")
#     page.set_viewport_size({"width": 1670, "height": 890})
#     page.add_init_script("""
#             Object.defineProperty(navigator, 'webdriver', {
#                 get: () => undefined
#             })
#         """)
#     yield page
#
#     LoggerUtils().logger().info("测试完成，关闭页面！！！")
#     # page.close()
#     LoggerUtils().logger().info("关闭浏览器！！！")

@pytest.fixture(scope="function", autouse=True)
def page(playwright: Playwright):
    LoggerUtils().logger().info("打开浏览器！！！")
    browser = playwright.chromium.launch(
        # 开启有界面方式运行，默认是无界面方式
        headless=False,
        # 设置超时时间，超出15秒结束运行
        timeout=15000,
        slow_mo=100,  # 减慢操作速度，便于调试
        args=['--start-maximized'],  # 最大化窗口
    )
    context = browser.new_context(
                                  # 设置base_url，便于后续使用
                                  base_url=TEST_URL,
                                  no_viewport=True,
                                  ignore_https_errors=True)
    page = context.new_page()
    # 等到页面加载完毕
    page.wait_for_load_state("networkidle")
    # 先进行登陆操作，为了后续的测试执行，提前登录
    LoginPage(page).login('10', "111111")
    yield page
    # 测试完成之后关闭浏览器
    # page.close()
    LoggerUtils().logger().info("测试完成，关闭页面！！！")
    context.close()
    # 测试完成之后关闭浏览器
    browser.close()
    LoggerUtils().logger().info("关闭浏览器！！！")





def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    在pytest测试运行结束时统计测试结果。
    :param config:
    :param exitstatus:
    :type terminalreporter: object
    """
    # 获取测试用例总数

    collected = terminalreporter._numcollected
    print(f"总计: {collected}")

    # 统计各种测试结果的数量
    failed = len(terminalreporter.stats.get('failed', []))
    error = len(terminalreporter.stats.get('error', []))
    passed = len(terminalreporter.stats.get('passed', []))
    skipped = len(terminalreporter.stats.get('skipped', []))
    rerun = len(terminalreporter.stats.get('rerun', []))

    duration = time.time() - terminalreporter._sessionstarttime

    # 打印结果
    print(f"通过: {passed}")
    print(f"失败: {failed}")
    print(f"异常: {error}")
    print(f"跳过: {skipped}")
    print(f"重跑: {rerun}")
    print(f"总耗时: {duration:.2f}秒")
    # 发送邮箱
    # send_email(Case_report=collected, passed=passed, failed_num=failed, skipped=skipped, reruns=rerun, error_num=error,
    #            duration=duration)

    # 发送飞书
    inform(Case_report=collected, passed=passed, failed_num=failed, skipped=skipped, reruns=rerun, error_num=error,
           duration=duration)
